// 版权归 瞄你个汪 所有。使用本代码应遵守相关法律法规和Apache 2.0开源许可要求。
package top.geeke.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.geeke.config.SysUserSessionManager;
import top.geeke.entity.SysMenu;
import top.geeke.mapper.SysMenuMapper;
import top.geeke.mapper.dto.MenuOutput;
import top.geeke.service.ISysMenuService;

import java.util.*;

/**
 * <p>
 * 系统菜单表 服务实现类
 * </p>
 * @author 瞄你个汪
 * @since 2024-01-01 12:00:00
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
    @Autowired
    private SysUserSessionManager sysUserSessionManager;
    @Override
    public List<MenuOutput> getMenuList() {
        if (sysUserSessionManager.isSuperAdmin()) return toMenuTree(baseMapper.getAllMenuList());
        Long userId = sysUserSessionManager.getUserId();
        List<MenuOutput> menuList = baseMapper.getMenuList(userId);
        return toMenuTree(menuList);
    }

    @Override
    public List<String> getPermissions() {
        if (sysUserSessionManager.isSuperAdmin()) return baseMapper.getAllPermissions();
        Long userId = sysUserSessionManager.getUserId();
        return baseMapper.getPermissions(userId);
    }

    /**
     * 将列表菜单转为树结构菜单
     * @param list 列表菜单
     * @return 树结构菜单
     */
    private List<MenuOutput> toMenuTree(Collection<MenuOutput> list) {
        List<MenuOutput> treeMenu = new ArrayList<>();
        list.forEach(m ->  { if (m.getPId() == 0) treeMenu.add(m); });

        Queue<MenuOutput> queue = new LinkedList<>(treeMenu);

        while (!queue.isEmpty()) {
            MenuOutput temp = queue.poll();

            // 渲染菜单额外参数
            temp.renderSysMenuMeta();

            List<MenuOutput> children = new ArrayList<>();
            list.forEach(m -> { if (temp.getId().equals(m.getPId())) children.add(m); });
            if (!children.isEmpty()) {
                queue.addAll(children);
                temp.setChildren(children);
            }
        }

        return treeMenu;
    }
}
